<template>
  <el-container style="height: 80%; margin: 20px;">
    <el-header class="header">
      <h1>Chat Room</h1>
    </el-header>
    <el-main>
      <el-scrollbar wrap-class="scrollbar-wrapper">

        <div v-for="msg in messages" :key="msg.timestamp" class="message-item" :class="{right:msg.name===user.name}"  >
          <img :src="msg.avatar" alt="" class="chat-avatar" :class="{right:msg.name===user.name}">
          <div class="message-content">
            <div class="message-header">
              <span class="username" :class="{right:msg.name===user.name}">{{ msg.name }}</span>
              <span class="date" :class="{right:msg.name===user.name}">{{ msg.time }}</span>
            </div>
            <p  class="message-bubble" :class="{own_bubble:msg.name===user.name}"> {{ msg.content }}</p>
          </div>
        </div>
      </el-scrollbar>
    </el-main>
    <el-footer>
      <el-input v-model="message" style="width: 80%; min-height: 10px; font-size: 16px;" placeholder="开始聊天吧！📱💻" @keyup.enter="sendMessage" clearable>
        <template #append>
          <el-button type="primary" style="max-height: 10px;" icon="el-icon-send" @click="sendMessage">Send</el-button>
        </template>
      </el-input>
    </el-footer>
  </el-container>
</template>

<script>
export default {
  data() {
    return {
      user: JSON.parse(sessionStorage.getItem('xm-user') || '{}'),
      message: '',
      messages: [],
      socket: null,
    };
  },
  mounted() {
    this.socket = new WebSocket('ws://localhost:9090/chat?userid=' + this.user.userId);
    this.socket.onopen = () => {
      this.$message.success("您已成功进入聊天室");
      console.log('WebSocket connection established');
    };
    this.socket.onmessage = (event) => {
      const msg = JSON.parse(event.data)

      this.messages.push({
        time: msg.timestamp,
        avatar: msg.avatar,
        name: msg.name,
        content: msg.content,
        timestamp: msg.timestamp
      });
    };
    this.socket.onerror = (error) => {
      this.$message.success("连接错误，请刷新重试");
      console.error('WebSocket error:', error);
    };
    this.socket.onclose = (event) => {
      this.$message.success("与聊天室的连接断开");
      console.log('WebSocket connection closed:', event);
    };
  },
  methods: {
    sendMessage() {
      if (this.message.trim() !== '' && this.socket.readyState === WebSocket.OPEN) {

        const date = new Date();

        const formatter = new Intl.DateTimeFormat('zh-CN', {
          year: 'numeric',
          month: 'long',
          day: '2-digit',
          hour: 'numeric',
          minute: '2-digit',
          hour12: false,  // 使用 12 小时制
          timeZone: 'Asia/Shanghai'
        });

        const isoTimestamp = formatter.format(date);
        const msgToSend = JSON.stringify({
          content: this.message,
          userId: this.user.id,
          avatar: this.user.avatar,
          name: this.user.name,
          timestamp: isoTimestamp
        });
        // 发送序列化后的 JSON 字符串
        this.socket.send(msgToSend);
        this.message = '';  // 清空消息输入以便下一次发送
      }
    },
  },
};
</script>

<style scoped>
.header {
  border: 2px solid white;
  border-radius: 10px;
  background-color: #ffffff;
  height: 300px;
  font-size: large;
  min-width: 100%;

}
.scrollbar-wrapper {
  height: 150px;
  display: flex;
  flex-direction: column;
  width: 100%; 
  align-items: flex-end; /* Align children to the right */
}
/* 左对齐 */
.message-item {
  display: flex;
  float: left;
  clear: both;
  min-width: 10%;
  align-items: center; /* 对齐到顶部 */
  margin-bottom: 10px;
  padding: 10px;
; /* Make sure the container shrinks to fit the content */
  border-bottom: 1px solid #efefef;
}
/* 右对齐 */
.message-item.right{
  float: right;
}

.chat-avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  margin-right: 10px;
  /* 在图片和名字之间添加一些间距 */
}

.chat-avatar.right{
  order:1000;
  margin-left: 10px;
}
.message-content {
  flex: 1;
}
.message-header{
  display: flex;
  justify-content: space-between;
  align-items: baseline;
  max-width: 700px;
  min-width: 200px;
  padding: 0px;
  /* 添加一些内边距 */
}

.username {
  order: 1;
  font-weight: bold;
}
.username.right {
  order: 2;
}
.date {
  order: 2;
  font-size: 0.8rem;
  color: grey;
}
.date.right {
  order: 1;
}
.message-bubble {
  background-color: white;
  white-space: normal;
  word-wrap: break-word;
  padding: 15px;
  border-radius: 15px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.2); /* 气泡阴影 */
  margin-top: 5px;
  max-width: 700px;
  min-width: 200px;
  position: relative; /* 相对定位用于气泡效果 */
  color: black; /* 黑色文字 */
}
.message-bubble.own_bubble {
  background-color: #800080; /* 紫色气泡 */
  color: white;
  align-self: flex-start;
}
</style>